<?php
            
use app\model\Record; 
use app\model\Fee; 
use app\model\Comm; 
use app\model\Theme; 
use app\model\Poster; 
use app\model\Worker; 
use app\model\Order; 
use app\model\Userdata; 


/**
 * Author: cbw
 * Desc: 红包雨
 * Time: 2021/12/30 9:11 下午
 * Email: 17854288794@163.com
 */
require_once PATH_MODULE .'define.php';
class RedRainModel extends PluginModel
{
    //基础信息检测
    public static function checkBaseError($theme)
    {
        global $_P, $_G, $_S, $_C;
        $error_text = '';
        $now_time = time();
        if (!$theme) {
            return modelShow(40002);
        }
        if ($theme['begintime'] > $now_time) {
            return modelShow(40064);
        }
        if ($now_time > $theme['endtime']) {
            return modelShow(40065);
        }
        if ($theme['status'] == '2') {
            return modelShow(40065);
        }
        return $error_text;
    }
    //红包雨通用验证
    public static function redrainBaseCheck($themeid,$fans,$config){
        $now = time();
        //员工不可参与
        if(!$config['redrain_has_worker']&&is_worker($themeid)){
            $code = 100;
            $msg = '员工不可参与';
            return modelShow($code,$msg);
        }

        if ($now<$config['redrain_begintime']){
            $code = 101;
            $msg = '红包雨活动未开始';
            return modelShow($code,$msg);
        }

        if($now>$config['redrain_endtime']){
            $code = 102;
            $msg = '红包雨活动已结束';
            return modelShow($code,$msg);
        }

        //是否有红包使用记录
        $used_redrain = self::getUserRedRainFlagTotal($themeid, $fans['uid'], 1);
        if($used_redrain>0){
            $code = 104;
            $msg = '已有红包使用，不可参与';
            return modelShow($code,$msg);
        }

        //时间段返回
        $redrain_times = $config['redrain_times'];
        $now_date = date('Y-m-d',time());
        $now_time = date('Y-m-d H:i',time());
        $in_time = 0;
        if($redrain_times){
            foreach ($redrain_times  as $v){
                $time = explode('-',$v);
                $begintime = $now_date.' '.$time[0];
                $endtime = $now_date.' '.trim($time[1]);
                if($now_time>=$begintime&&$now_time<=$endtime){
                    $in_time = 1;
                }
            }
        }else{
            $in_time = 1;
        }

        if(!$in_time){
            $code = 105;
            $msg = '不在红包雨活动时间范围内';
            return  modelShow($code,$msg);
        }
        //红包雨总金额和每日金额的验证
        $redrain_validity = $config['redrain_validity'];
        //存在总金额限制和每日金额限制
        if ($config['redrain_total_amount'] > 0 && $config['redrain_day_amount'] > 0) {
            //判断所有用户有效期内的最大红包金额总和 是否大于奖金池
            $remain_amount = self::formatAllRedrainAmount($themeid, $config);
            $day_remain_amount = self::allDayMaxAmount($themeid,$config,$redrain_validity);
            if($remain_amount<=0){
                $code = 108;
                $msg = '已达最大金额上限';
                return modelShow($code,$msg);
            }elseif ($day_remain_amount<=0) {
                $code = 109;
                $msg = '已达今日最大金额上限，请明日再来';
                return modelShow($code,$msg);
            }
        }
        //最大金额限制
        elseif ($config['redrain_total_amount'] > 0&& $config['redrain_day_amount']==0) {
            //判断所有用户有效期内的最大红包金额总和 是否大于奖金池
            $remain_amount = self::formatAllRedrainAmount($themeid, $config);
            if ($remain_amount <= 0) {
                $code = 108;
                $msg = '已达最大金额上限';
                return modelShow($code,$msg);
            }
        }
        //每日金额限制
        elseif($config['redrain_day_amount'] > 0 && $config['redrain_total_amount'] ==0){
            //判断是否超过今日最大金额
            $day_remain_amount = self::allDayMaxAmount($themeid,$config,$redrain_validity);
            if ($day_remain_amount <= 0) {
                $code = 109;
                $msg = '已达今日最大金额上限，请明日再来';
                return modelShow($code,$msg);
            }
        }
        return modelShow(0,'验证通过');
    }

    /**
     * Desc:获取用户机会列表数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/12 9:09 上午
     * @param $themeid
     * @param int $type
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getUserRedRainChanceFlag($themeid, $type = 0, $page_start = 0, $page_size = 10)
    {
        $condition = "";
        if ($type) {
            $condition .= " and a.type='" . $type . "'";
        }
        $condition .= " order by a.created_at desc ";
        if ($page_size) {
            $condition .= "  limit " . $page_start . "," . $page_size;
        }

        $sql = " select a.*,b.id as fan_id,b.username,b.avatar,b.nickname,b.username,b.jihui,b.mobile,c.nickname as from_nickname  from " . tablename(t_redrain_user_chance) . " as a " .
            "left join " . tablename(t_fans) . " as b on b.uid = a.uid and b.themeid=$themeid" .
            " left join " . tablename(t_fans) . " as c on a.from_uid = c.uid and c.themeid=$themeid" .
            " where a.themeid=$themeid  " . $condition;
        return db_select($sql);
    }

    /**
     * Desc:获取机会类型对应的数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/12 9:09 上午
     * @param $themeid
     * @return array[]
     */
    public static function getUserChanceTypeArr($themeid)
    {
        $temp = [
            ['title' => '全部', 'type' => 0, 'total' => 0],
            ['title' => '商家赠送', 'type' => 4, 'total' => 0],
            ['title' => '转发朋友圈', 'type' => 1, 'total' => 0],
            ['title' => '好友助力', 'type' => 2, 'total' => 0],
            ['title' => '转发好友', 'type' => 3, 'total' => 0],
            ['title' => '管理员添加', 'type' => 5, 'total' => 0],
            ['title' => '机会使用', 'type' => -1, 'total' => 0],
            ['title' => '好友下单', 'type' => 9, 'total' => 0],
        ];
        foreach ($temp as $k => $val) {
            $temp[$k]['total'] = self::getUserChanceTotal($themeid, 0, $val['type']);
        }
        return $temp;
    }

    /**
     * Desc:获取对应类型的机会数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/12 9:07 上午
     * @param $themeid
     * @param int $uid
     * @param int $type
     * @return int
     */
    public static function getUserChanceTotal($themeid, $uid = 0, $type = 0)
    {
        $condition = " where themeid=$themeid";
        if ($uid) {
            $condition .= " and uid=$uid";
        }
        if ($type) {
            $condition .= " and type=$type";
            if ($type==1 ||  $type==3){
                $condition  .= " and chance  > 0";
            }
        }
        $sql = " select count(*) as cnt from " . tablename(t_redrain_user_chance) . $condition;
        return db_find($sql)['cnt'];
    }

    /**
     * Desc:获取未使用机会的用户列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/12 9:19 上午
     * @param $themeid
     * @param int $page_start
     * @param int $page_size
     * @param string $search
     * @return array
     */
    public static function getNoUsedUserList($themeid, $page_start = 0, $page_size = 0, $search = '',$count = false)
    {
        $sql1 = "select uid from " . tablename(t_redrain_user_chance) . " where chance >0 and themeid=$themeid group by uid";
        $res1 = db_select($sql1);
        $sql2 = "select uid from " . tablename(t_redrain_user_chance) . " where chance =-1 and themeid=$themeid group by uid";
        $res2 = db_select($sql2);
        $add_arr = [];
        $used_arr = [];
        $diff_arr = [];

        foreach ($res1 as $key => $val) {
            if(!empty($val['uid'])){
                array_push($add_arr, $val['uid']);
            }
        }
        foreach ($res2 as $k => $v) {
            if(!empty($v['uid'])){
                array_push($used_arr, $v['uid']);
            }
        }

        $diff_arr = array_diff($add_arr, $used_arr);

        if (!$diff_arr) {
            if ($count) {
                return 0;
            }
            return [];
        } else {
            $diff_uid = '';
            foreach ($diff_arr as $kk => $vv) {
                $diff_uid .= $vv . ',';
            }
            $diff_uid = '(' . rtrim($diff_uid, ',') . ')';
            $condition = "";
            if ($search) {
                $condition .= " and a.nickname like '" . $search . "'" . " or a.mobile like '" . $search . "' " . " or a.username like '" . $search . "' ";
            }
            $condition .= " group by b.uid";
            if ($page_size && !$count) {
                $condition .= " LIMIT " . $page_start . "," . $page_size;
            }
            $sql = "  from " . tablename(t_fans) . " as a " .
                "left join " . tablename(t_redrain_user_chance) . " as b on a.uid=b.uid and b.themeid=$themeid" .
                " where a.themeid=$themeid and a.uid in $diff_uid " . $condition;
            if ($count){
                return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
            }else{
                $sql = " select a.uid,a.nickname,a.avatar,a.username,a.mobile,a.jihui ".$sql;
                return db_select($sql);
            }

        }
    }

    /**
     * Desc:搜索机会记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/12 9:36 上午
     * @param $themeid
     * @param $search
     * @param int $page_start
     * @param int $page_size
     * @param $start_day
     * @param $end_day
     * @return mixed
     */
    public static function searchUserRedRainChanceFlag($themeid,$type,$search, $page_start = 0, $page_size = 10, $start_day, $end_day,$uid=0)
    {
        $condition = "";
        if ($type) {
            $condition .= " and a.type='" . $type . "'";
            if ($type==1 ||  $type==3){
                $condition .= " and a.chance>0";
            }
        }

        if($uid>0){
            $condition .= " and a.uid=$uid";
        }

        if ($search) {
            $condition .= " AND (b.nickname LIKE '" . $search . "'" . " or b.mobile LIKE '" . $search . "' " . " or b.username LIKE '" . $search . "' )";
        }
        if ($start_day && $end_day) {
            $condition .= "  and a.created_at between '" . $start_day . "' and '" . $end_day . "'";
        }
        $condition .= " ORDER BY a.created_at DESC ";
        if ($page_start) {
            $condition .= "LIMIT " . $page_start . "," . $page_size;
        }

        $sql = " SELECT a.*,b.id as fan_id,b.username,b.avatar,b.nickname,b.username,b.jihui,b.mobile,c.nickname as from_nickname FROM " . tablename(t_redrain_user_chance) . " AS  a " .
            " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and b.themeid=$themeid" .
            " left join " . tablename(t_fans) . " as c on a.from_uid = c.uid and c.themeid=$themeid" .
            " WHERE a.themeid=$themeid" . $condition;

        return db_select($sql);
    }

    /**
     * Desc:获取用户剩余红包雨抽奖机会数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/12 9:47 上午
     * @param $config
     * @param $fans
     * @param $themeid
     * @return mixed
     */
    public static function getUserRemainChance($config, $fans, $themeid)
    {
        $sql = " select count(*) as cnt from " . tablename(t_redrain_user_flag) . " where themeid=$themeid and uid='{$fans['uid']}' and chance<0 and type=-1";
        $used_flag_total = db_find($sql)['cnt'];
        $tempa = $fans['jihui'] + $used_flag_total;
        if ($tempa > $config['redrain_chance_limit']) {
            $remain_num = max(0, ($config['redrain_chance_limit'] - $used_flag_total));
        } else {
            $remain_num = $fans['jihui'];
        }
        return $remain_num;
    }

    /**
     * Desc:获取红包获取记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/12 9:32 上午
     * @param $themeid
     * @param int $status
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getUserRedRainFlag($themeid, $status = -1, $page_start = 0, $page_size = 10)
    {
        $condition = "";
        if ($status > -1) {
            $condition .= " and a.status='" . $status . "'";
        }
        if ($page_size) {
            $condition .= "  limit " . $page_start . "," . $page_size;
        }
        $sql = " select a.*,b.username,b.avatar,b.nickname from " . tablename(t_redrain_user_flag) . " as a " .
            "left join " . tablename(t_fans) . " as b on b.uid = a.uid and b.themeid=$themeid" .
            " where a.themeid=$themeid  " . $condition;
        return db_select($sql);
    }

    /**
     * Desc:获取对应类型的红包记录的数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/12 9:33 上午
     * @param $themeid
     * @return array[]
     */
    public static function getUserFlagStatusArr($themeid)
    {
        $temp = [
            ['title' => '全部', 'status' => -1, 'total' => 0],
            ['title' => '已获取，未提现', 'status' => 0, 'total' => 0],
            ['title' => '已提现', 'status' => 1, 'total' => 0],
            ['title' => '已过期', 'status' => 2, 'total' => 0],
        ];
        foreach ($temp as $k => $val) {
            $temp[$k]['total'] = self::getUserFlagTotal($themeid, 0, $val['status']);
        }
        return $temp;
    }

    /**
     * Desc:获取对应类型的红包记录数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/12 9:32 上午
     * @param $themeid
     * @param int $uid
     * @param int $status
     * @return int
     */
    public static function getUserFlagTotal($themeid, $uid = 0, $status = -1)
    {
        $condition = " where themeid=$themeid";
        if ($uid) {
            $condition .= " and uid=$uid";
        }
        if ($status > -1) {
            $condition .= " and status=$status";
        }
        $sql = " select count(*) as cnt from " . tablename(t_redrain_user_flag) . $condition;
        return (int)db_find($sql)['cnt'];
    }

    /**
     * Desc:搜索红包记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/12 9:48 上午
     * @param $themeid
     * @param $search
     * @param int $page_start
     * @param int $page_size
     * @param $start_day
     * @param $end_day
     * @return mixed
     */
    public static function searchUserFlag($themeid, $status,$search, $page_start = 0, $page_size = 10, $start_day, $end_day,$uid=0,$count = false)
    {
        global $_G,$_P,$_S,$_C;
        $condition = "";
        if ($status > -1) {
            $condition .= " and a.status='" . $status . "'";
        }
        if ($search) {
            $condition .= " AND (b.nickname LIKE '" . $search . "'" . " or b.mobile LIKE '" . $search . "' " . " or a.convert_code LIKE '" . $search . "') ";
        }
        if ($uid > 0) {
            $condition .= " and a.uid= $uid";
        }
        if ($start_day && $end_day) {
            $condition .= "  and a.created_at between '" . $start_day . "' and '" . $end_day . "'";
        }
        $condition .= " ORDER BY a.created_at DESC ";
        if ($page_start && !$count) {
            $condition .= "LIMIT " . $page_start . "," . $page_size;
        }
        $sql = "  FROM " . tablename(t_redrain_user_flag) . " AS  a " .
            " LEFT JOIN " . tablename(t_fans) . " AS b on a.uid=b.uid and a.themeid = b.themeid" .
            " WHERE a.themeid=$themeid" . $condition;
        if ($count){
            return  intval(db_fetchcolumn ( 'SELECT COUNT(*)'.$sql));
        }else{
            $sql = "  SELECT a.*,b.avatar,b.nickname,b.username,b.mobile,b.workerid " . $sql;
            $list =  db_select($sql);
            foreach($list as $k => $val){
                $r = Worker::getWokerName($_S,$themeid,$val['workerid']);
                $list[$k]['workername'] = $r['workername'];
                $themyrecord = Record::getLastGroupByUid($val['uid'],$themeid);
                if (!$themyrecord){
                    $list[$k]['order_info']='用户未付款';
                }else{
                    if ($themyrecord['status']==1){
                        $list[$k]['order_info']='用户已付款';
                    }elseif ($themyrecord['status']==0){
                        $list[$k]['order_info']='用户未付款';
                    }
                }
            }
            return $list;
        }


    }

    /**
     * Desc:获取基础信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 9:37 上午
     * @param $themeid
     * @param $fans
     * @param $config
     * @param $from_uid
     * @param $system
     */
    public static function getBaseInfo($themeid, $fans, $config, $from_uid, $system)
    {
        //更新已存在红包记录过期时间
        if(!isset($fans['uid'])){
            $fans['uid'] = 0;
        }
        //  self::getUserCanUseRedRainFlag($themeid, $fans['uid'], $config, $system);

        $has_redrain_amount = false;
        $fans_has_redrain_flag = false;
        $fans_jihui = 0;

        $now = time();
        $in_redrain_time = 1;
        $can_join = 1;        //是否能参与
        $can_help = false;    //是否能助力
        $in_time = 0;         //是否在红包雨时间段内
        $redrain_alert_icon = $config['redrain_alert_icon'];
        //红包雨时间
        if ($now<$config['redrain_begintime']||$now>$config['redrain_endtime']){
            $in_redrain_time = 0;
        }
        //员工不可参与
        if(!$config['redrain_has_worker']&&is_worker($themeid)){
            $can_join = 0;
        }
        //是否是自己
        if ($from_uid != $fans['uid']) {
            $can_help = true;
        }

        $redrain_validity = $config['redrain_validity'];
        //存在总金额限制和每日金额限制
        if ($config['redrain_total_amount'] > 0 && $config['redrain_day_amount'] > 0) {
            //判断所有用户有效期内的最大红包金额总和 是否大于奖金池
            $remain_amount = self::formatAllRedrainAmount($themeid, $config);
            $day_amount = self::allDayMaxAmount($themeid,$config,$redrain_validity);

            if ($remain_amount > 0 && $day_amount>0) {
                $has_redrain_amount = true;
            }
        }
        //最大金额限制
        elseif ($config['redrain_total_amount'] > 0&& $config['redrain_day_amount']==0) {
            //判断所有用户有效期内的最大红包金额总和 是否大于奖金池
            $remain_amount = self::formatAllRedrainAmount($themeid, $config);
            if ($remain_amount > 0) {
                $has_redrain_amount = true;
            }
        }
        //每日金额限制
        elseif($config['redrain_day_amount'] > 0 && $config['redrain_total_amount'] ==0){
            //判断是否超过今日最大金额
            $day_all_amount = self::allDayMaxAmount($themeid,$config,$redrain_validity);
            if ($day_all_amount > 0) {
                $has_redrain_amount = true;
            }
        }
        //没有限制
        elseif($config['redrain_day_amount'] ==0 && $config['redrain_total_amount'] ==0){
            $has_redrain_amount = true;
        }

        //在活动时间内
        if($in_redrain_time==1&&$can_join==1){
            //判断商家机会是否存在
            $shangjia_chance_total = self::getUserChanceTotal($themeid, $fans['uid'], 4);
            if ($shangjia_chance_total < 1 && $config['redrain_shangjia_num'] > 0) {
                //不存在商家赠送机会 插入商家赠送机会
                self::apiInsertChance($themeid, $config, $fans, 4, $from_uid);
                $fans['jihui'] = db_getcolumn(t_fans, array('uid' => $fans['uid'], 'themeid' => $themeid), 'jihui');
            }

            //判断代言是否开启
            // if ($system['daiyan']){
            //判断邀请人：from_uid，与配置，增加好友到访记录与机会数
            //增加是否为他助力过判断
            $friend_help_flag_total = self::getFriendHelpFlagTotal($themeid, $from_uid, $fans['uid']);
            if ($from_uid && $fans['uid'] != $from_uid && ($config['redrain_friend_view_num'] > 0 && $config['redrain_friend_view_limit'] > 0) && $friend_help_flag_total == 0) {
                $new_time = time();
                $redrain_help_validity = $config['redrain_help_validity'];//助力有效期x小时
                $theme = Theme::getThemeById($themeid);
                $validate_time = $theme['endtime'];//默认助力截止时间为活动结束时间
                //查找邀请人的第一次助力时间
                $first_flag = self::getFirstHelpFlag($themeid, $from_uid);
                if (!empty($first_flag) && $redrain_help_validity > 0) {
                    $first_flag_time = strtotime($first_flag['created_at']);
                    $validate_time2 = strtotime("+$redrain_help_validity hour", $first_flag_time);//助力截止时间
                    if ($validate_time2 < $validate_time) {
                        $validate_time = $validate_time2;
                    }
                }
                //增加判断，助力达到上限，不写入助力记录表；未获取助理人信息：nickname=='新用户'，也无法助力；
                $current_type_success_total = self::getAddFlagTotalByType($from_uid, $themeid, 2, true, false);
                if ($new_time < $validate_time && $current_type_success_total < $config['redrain_friend_view_limit'] && trim($fans['avatar']) != 'https://css2020.yixuan.net/2020css/yx2020/images/question.png') {
                    //在助力时间范围内
                    $from_fans = self::getFansInfoByWhere(['themeid' => $themeid, 'uid' => $from_uid]);
                    if (!empty($from_fans)) {
                        self::apiInsertChance($themeid, $config, $from_fans, 2, $fans['uid']);
                    }
                }
            }

            //时间段返回
            $redrain_times = $config['redrain_times'];
            $now_date = date('Y-m-d',time());
            $now_time = date('Y-m-d H:i',time());
            if($redrain_times){
                foreach ($redrain_times  as $v){
                    $time = explode('-',$v);
                    $begintime = $now_date.' '.$time[0];
                    $endtime = $now_date.' '.trim($time[1]);
                    if($now_time>=$begintime&&$now_time<=$endtime){
                        $in_time = 1;
                    }
                }
            }else{
                $in_time = 1;
            }

            $not_used = 1;
            //红包记录
            $used_redrain = self::getUserRedRainFlagTotal($themeid, $fans['uid'], 1);
            if($used_redrain){
                $not_used = 0;
            }
            //在活动时间 在设置的时间段  未超设置金额
            if (!$in_time || !$not_used || !$has_redrain_amount) {
                $redrain_alert_icon = '';
            }
        }else{
            $redrain_alert_icon = '';
        }

        //判断用户是否存在红包记录
        $fans_redrain_falg = self::getUserRedRainFlagTotal($themeid, $fans['uid']);
        if ($fans_redrain_falg > 0) {
            $fans_has_redrain_flag = true;
        }
        $fans_jihui = min($fans['jihui'], $config['redrain_chance_limit']);

        //右侧浮标是否显示
        $redrain_right_icon = $config['redrain_right_icon'];


        $new_fans = self::getFansInfoByWhere(['themeid' => $themeid, 'uid' => $fans['uid']]);

        return [
            'has_redrain_amount' => $has_redrain_amount,
            'fans_has_flag' => $fans_has_redrain_flag,
            'can_help' => $can_help,
            'remain_chance' => (int)$fans_jihui,
            'redrain_right_icon' => $redrain_right_icon,//右侧浮标
            'redrain_alert_icon' => $redrain_alert_icon,//全屏红包弹窗
            'chances' => intval($new_fans['jihui']),//剩余抽奖机会
        ];
    }


    /**
     * Desc:增加或减少机会 并插入记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/13 8:08 下午
     * @param $themeid
     * @param $config
     * @param $fans
     * @param $type
     * @param $from_uid
     */
    public static function apiInsertChance($themeid, $config, $fans, $type, $from_uid)
    {
        $admin_name = '';
        $main_chance_limit = $config['redrain_chance_limit'];
//        $history_user_chance = $fans['jihui'];//应该查获得总机会数，sum(chance)
        $sql = "select sum(chance) as cnt from " . tablename(t_redrain_user_chance) .
            " where themeid=$themeid and type > 0 and chance > 0 and uid=" . $fans['uid'];
        $history_user_chance = db_find($sql)['cnt'];
        $add_chance = self::getTypeChance($type, $config, $themeid, $fans, $from_uid);
        if ($add_chance > 0 && $history_user_chance >= $main_chance_limit) {
            $admin_name = '达到机会上限';
            $add_chance = 0;
        }
        //奖金池存在奖金
        //判断所有用户有效期内的最大红包金额总和 是否大于奖金池
        if($config['redrain_total_amount']>0){
            $remain_amount = self::formatAllRedrainAmount($themeid, $config);
            if ($remain_amount <= 0) {
                $admin_name = '红包金额已发放完';
                $add_chance = 0;
            }
        }


        //查找是否有已使用红包
        $used_redrain = self::getUserRedRainFlagTotal($themeid, $fans['uid'], 1);
        if ($used_redrain > 0) {
            $admin_name = '已使用红包';
            $add_chance = 0;
        }
        //将要增加的机会与总剩余机会做比较
        if ($add_chance > 0 && $main_chance_limit > $history_user_chance && $add_chance > ($main_chance_limit - $history_user_chance)) {
            $add_chance = $main_chance_limit - $history_user_chance;
        }
        $insert_data = [
            'uid' => $fans['uid'],
            'themeid' => $themeid,
            'type' => $type,
            'chance' => $add_chance,
            'is_tips' => 0,
            'from_uid' => $from_uid,
            'admin_name' => $admin_name,
        ];
        //查找新用户机会信息
        $new_fans = self::getFansInfoByWhere(['themeid' => $themeid, 'uid' => $fans['uid']]);
        $insert_data['changed_chance'] = $new_fans['jihui'] + $add_chance;
        // used_id 使用的机会ID，used_type 使用的机会来源，0未使用 1转发朋友圈 2好友到访 3转发好友 4商家赠送 5管理员增加 9好友下单，remaining_chance 剩余的机会，changed_chance 变化后的机会数
        if ($add_chance > 0){
            //增加机会
            $insert_data['used_id'] = 0;
            $insert_data['used_type'] = 0;
            $insert_data['remaining_chance'] = $add_chance;
        }elseif ($add_chance < 0){
            //使用机会
            //查找最早获得，剩余机会>0的机会信息
            $sql = "select * from " . tablename(t_redrain_user_chance) .
                " where themeid=$themeid and type > 0 and chance > 0 and remaining_chance > 0 and uid=" . $fans['uid'].' order by created_at asc ';
            $usedChance = db_find($sql);
            if ($usedChance){
                $insert_data['used_id'] = $usedChance['id'];
                $insert_data['used_type'] = $usedChance['type'];
                $insert_data['remaining_chance'] = 0;
                //更新机会表剩余机会-1
                $where = ['themeid' => $themeid, 'uid' => $fans['uid'], 'id' => $usedChance['id']];
                $update_data = ['remaining_chance' => $usedChance['remaining_chance']+$add_chance];
                self::updateFansRedRainChance($where, $update_data);
            }else{
                return 0;
            }
        }
        //用户日志收集
        $log_msg = '获得红包雨机会'.$add_chance;
        if ($admin_name=='达到机会上限'){
            $log_msg.= ','.$admin_name;
        }
        if ($type==2){
            Userdata::addLog($themeid, $fans['uid'], 27, $log_msg,0,$from_uid);
        }else{
            Userdata::addLog($themeid, $fans['uid'], 33, $log_msg);
        }

        $res = self::insertUserChance($insert_data);
        if ($add_chance != 0 && $res) {
            $new_user_chance = $new_fans['jihui'] + $add_chance;
            $update_data = [
                'jihui' => $new_user_chance
            ];
            //用户日志收集
            $log_msg = '获得红包雨机会'.$add_chance;
            $log_msg.=',当前机会'.$new_user_chance;
            if ($type==2){
                Userdata::addLog($themeid, $fans['uid'], 27, $log_msg,0,$from_uid);
            }else{
                Userdata::addLog($themeid, $fans['uid'], 33, $log_msg);
            }
            $res1 = self::updateFansInfo($fans['uid'], $themeid, $update_data);
        }
        return $res;
    }
    //更新活动机会记录
    public static function updateFansRedRainChance($where, $update_data)
    {
        $update_data['updated_at'] = date("Y-m-d H:i:s", time());
        $res = db_update(t_redrain_user_chance, $update_data, $where);
        if (!$res) {
            return false;
        } else {
            return true;
        }
    }

    //更新活动粉丝表信息
    public static function updateFansInfo($uid, $themeid, $update_data)
    {
        $res = db_update(t_fans, $update_data, ['uid' => $uid, 'themeid' => $themeid]);
        if (!$res) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Desc:获取用户信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/13 8:33 下午
     * @param $where
     * @return mixed
     */
    public static function getFansInfoByWhere($where)
    {
        return db_get(t_fans, $where);
    }

    /**
     * Desc:获取对应类型的增加、减少机会次数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/13 2:07 下午
     * @param $type
     * @param $config
     * @param $themeid
     * @param $fans
     * @param $from_uid
     * @return int
     */
    public static function getTypeChance($type, $config, $themeid, $fans, $from_uid)
    {
        $add_chance = 0;
        switch ($type) {
            case 1:
                //转发朋友圈
                //判断是否存在分享朋友圈的记录  以及今日记录数
                $all_flag_total = self::getFlagTotal($fans['uid'], $themeid, $type);
                if ($all_flag_total < 3) {
                    //小于3天
                    if ($all_flag_total == 0) {
                        //第一天
                        $add_chance = $config['redrain_first_share_moment'];
                    } elseif ($all_flag_total == 1) {
                        //第二天
                        $today_type_success_total = self::getAddFlagTotalByType($fans['uid'], $themeid, $type, true, true);
                        if (!$today_type_success_total) {
                            $add_chance = $config['redrain_second_share_moment'];
                        }
                    } elseif ($all_flag_total == 2) {
                        //第三天
                        $today_type_success_total = self::getAddFlagTotalByType($fans['uid'], $themeid, $type, true, true);
                        if (!$today_type_success_total) {
                            $add_chance = $config['redrain_third_share_moment'];
                        }
                    }
                }
//                if ($config['redrain_share_moment_num']>0 && $config['redrain_share_moment_limit_day']>0){
//                    $has_flag_num = self::getFlagTotal($fans['uid'],$themeid,$type,true);
//                    $new_flag_num = $has_flag_num+1;
//                    $current_type_success_total = self::getAddFlagTotalByType($fans['uid'],$themeid,$type);
//                    $today_type_success_total = self::getAddFlagTotalByType($fans['uid'],$themeid,$type,true,true);
//                    if ($current_type_success_total<$config['redrain_share_moment_limit_day']){//判断天数以及成功标记数
//                        //判断今日数量与配置每日数量 并今天没有成功记录
//                        if (($new_flag_num==$config['redrain_share_moment_num']) && $today_type_success_total<1){
//                            $add_chance = 1;
//                        }
//                    }
//                }
                break;
            case 2:
                if ($config['redrain_friend_view_num'] > 0 && $config['redrain_friend_view_limit'] > 0) {
                    //好友到访
                    //当前好友是否给助力过
                    //获取用户第一次好友助力记录
                    $first_flag = self::getFirstHelpFlag($themeid, $fans['uid']);
                    if (!$first_flag) {
                        //不存在第一次记录
                        if ($config['redrain_friend_view_num'] == 1) {
                            $add_chance = 1;
                        }
                    } else {
                        $new_time = time();
                        $redrain_help_validity = $config['redrain_help_validity'];
                        $first_flag_time = strtotime($first_flag['created_at']);
                        $validate_time = strtotime("+$redrain_help_validity hour", $first_flag_time);
                        if ($new_time < $validate_time) {
                            //判断是否助力过
                            $friend_help_flag_total = self::getFriendHelpFlagTotal($themeid, $fans['uid'], $from_uid);
                            if ($friend_help_flag_total < 1) {
                                //助力获得机会总数
                                $current_type_success_total = self::getAddFlagTotalByType($fans['uid'], $themeid, $type, true, false);
                                if ($current_type_success_total < $config['redrain_friend_view_limit']) {
                                    //未达到好友助力上限
                                    //判断助力总数量
                                    $history_type_flag_total = self::getFlagTotal($fans['uid'], $themeid, $type);
                                    $new_type_flag_total = $history_type_flag_total + 1;
                                    if ($new_type_flag_total % $config['redrain_friend_view_num'] == 0) {
                                        $add_chance = 1;
                                    }
                                }
                            }
                        }
                    }

//                    if (($config['redrain_help_begintime']<=$new_time) && ($new_time<$config['redrain_help_endtime'])){
//                        //在时间范围内
//                        $friend_help_flag_total = self::getFriendHelpFlagTotal($themeid,$fans['uid'],$from_uid);
//                        if ($friend_help_flag_total<1){
//                            $current_type_success_total = self::getAddFlagTotalByType($fans['uid'],$themeid,$type,true,false);
//                            if ($current_type_success_total<$config['redrain_friend_view_limit']){
//                                //未达到好友助力上限
//                                //判断助力总数量
//                                $history_type_flag_total = self::getFlagTotal($fans['uid'],$themeid,$type);
//                                $new_type_flag_total = $history_type_flag_total+1;
//                                if ($new_type_flag_total%$config['redrain_friend_view_num']==0){
//                                    $add_chance = 1;
//                                }
//                            }
//                        }
//                    }
                }


                break;
            case 3:
                //转发好友
                //判断是否存在转发好友的记录  以及今日记录数
                $all_flag_total = self::getFlagTotal($fans['uid'], $themeid, $type, false);
                if ($all_flag_total < 3) {
                    //小于3天
                    if ($all_flag_total == 0) {
                        //第一天
                        $add_chance = $config['redrain_first_share_friend'];
                    } elseif ($all_flag_total == 1) {
                        //第二天
                        $today_type_success_total = self::getAddFlagTotalByType($fans['uid'], $themeid, $type, true, true);
                        if (!$today_type_success_total) {
                            $add_chance = $config['redrain_second_share_friend'];
                        }
                    } elseif ($all_flag_total == 2) {
                        //第三天
                        $today_type_success_total = self::getAddFlagTotalByType($fans['uid'], $themeid, $type, true, true);
                        if (!$today_type_success_total) {
                            $add_chance = $config['redrain_third_share_friend'];
                        }
                    }
                }

//                if ($config['redrain_friend_view_num']>0 && $config['redrain_friend_view_limit']>0){
//                    //转发好友
//                    $has_flag_num = self::getFlagTotal($fans['uid'],$themeid,$type,true);
//                    $new_flag_num = $has_flag_num+1;
//                    $current_type_success_total = self::getAddFlagTotalByType($fans['uid'],$themeid,$type);
//                    $today_type_success_total = self::getAddFlagTotalByType($fans['uid'],$themeid,$type,true,true);
//                    if ($current_type_success_total<$config['redrain_share_friend_limit_day']){//判断天数以及成功标记数
//                        //判断今日数量与配置每日数量 并今天没有成功记录
//                        if (($new_flag_num==$config['redrain_share_friend_num']) && $today_type_success_total<1){
//                            $add_chance = 1;
//                        }
//                    }
//                }
                break;
            case 4:
                //商家赠送
                $add_chance = $config['redrain_shangjia_num'];
                break;
            case 9:
                //好友下单购买
                $add_chance = $config['redrain_friend_order_num'];
                break;
            case -1:
                //使用扣除
                $add_chance = -1;
                break;
            default:
                break;
        }
        return $add_chance;
    }

    /**
     * Desc:获取用户第一次到访记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/22 1:22 下午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getFirstHelpFlag($themeid, $uid)
    {
        $sql = " select * from " . tablename(t_redrain_user_chance) . " where themeid=$themeid and type=2 and uid=$uid order by id asc";
        return db_find($sql);
    }

    /**
     * Desc:获取查询条件下的记录数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/13 1:13 下午
     * @param $uid
     * @param $themeid
     * @param $type
     * @param false $is_today
     * @return int
     */
    public static function getFlagTotal($uid, $themeid, $type, $is_today = false)
    {
        if ($is_today) {
            $sql = "select count(*) as cnt from " . tablename(t_redrain_user_chance) .
                " where themeid=$themeid and type = $type and uid=$uid AND TO_DAYS(created_at) = TO_DAYS(NOW()) ";
            $count = intval(db_find($sql)['cnt']);
        } else {
            if($type==2){
                $sql = "select count(*) as cnt from " . tablename(t_redrain_user_chance) .
                    " where themeid=$themeid and type = $type and uid=$uid and chance>=0";
                $count = db_find($sql)['cnt'];
            }else{
                $sql = "select count(*) as cnt from " . tablename(t_redrain_user_chance) .
                    " where themeid=$themeid and type = $type and uid=$uid group by date_format(created_at, '%Y-%m-%d')";
                $count = count(db_find($sql)['cnt']);
            }
        }
        return $count;
    }


    //



    /**
     * Desc:获取对应类型下的用户的成功记录数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/13 1:27 下午
     * @param $uid
     * @param $themeid
     * @param $type
     * @return int
     */
    public static function getAddFlagTotalByType($uid, $themeid, $type, $is_add = true, $is_today = false)
    {
        if ($is_add) {
            if ($is_today) {
                $sql = " select count(*) as cnt from " . tablename(t_redrain_user_chance) .
                    " where themeid=$themeid and type = $type and uid=$uid and chance>0  AND TO_DAYS(created_at) = TO_DAYS(NOW()) ";
            } else {
                $sql = " select count(*) as cnt from " . tablename(t_redrain_user_chance) .
                    " where themeid=$themeid and type = $type and uid=$uid and chance>0 ";
            }
        } else {
            if ($is_today) {
                $sql = " select count(*) as cnt from " . tablename(t_redrain_user_chance) .
                    " where themeid=$themeid and type = $type and uid=$uid and chance<1  AND TO_DAYS(created_at) = TO_DAYS(NOW()) ";
            } else {
                $sql = "select count(*) as cnt from " . tablename(t_redrain_user_chance) .
                    " where themeid=$themeid and type = $type and uid=$uid and chance<1";
            }
        }
        return intval(db_find($sql)['cnt']);
    }

    /**
     * Desc:获取好友助力数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/13 1:45 下午
     * @param $themeid
     * @param $uid
     * @param $help_uid
     * @return int
     */
    public static function getFriendHelpFlagTotal($themeid, $uid, $help_uid)
    {
        $sql = "select count(*) as cnt from " . tablename(t_redrain_user_chance) .
            " where themeid=$themeid and type = 2 and uid=$uid  and from_uid=$help_uid ";
        return intval(db_find($sql)['cnt']);
    }

    /**
     * Desc:插入用户机会记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/13 2:12 下午
     * @param $data
     * @return false
     */
    public static function insertUserChance($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s", time());
        $res = $insertid = db_insert(t_redrain_user_chance, $data);
        if (!empty($res)) {
            return $insertid;
        } else {
            return false;
        }
    }

    /**
     * Desc:插入用户红包记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 5:33 下午
     * @param $data
     * @return false
     */
    public static function insertUserRedRain($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s", time());
        $res = $insertid = db_insert(t_redrain_user_flag, $data);
        if (!empty($res)) {
            return $insertid;
        } else {
            return false;
        }
    }

    /**
     * Desc:获取用户获得红包的记录数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 9:56 上午
     * @param $themeid
     * @param $uid
     * @return int
     */
    public static function getUserRedRainFlagTotal($themeid, $uid, $status = -1)
    {
        $condition = "";
        if (is_array($status)) {
            $statusStr = implode(",", $status);
            $condition .= " and status IN ( $statusStr )";
        } else {
            if ($status > -1) {
                $condition .= " and status=$status";
            }
        }
        $sql = "select count(*) as cnt from " . tablename(t_redrain_user_flag) .
            " where themeid=$themeid and uid=$uid " . $condition;
        return intval(db_find($sql)['cnt']);
    }

    /**
     * Desc:获取用户红包记录 区分分页 以及全部
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 10:13 上午
     * @param $themeid
     * @param int $uid
     * @param false $is_all
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */
    public static function getUserRedRainFlagList($themeid, $uid = 0, $is_all = false, $status = -1, $page_start = 0, $page_size = 10)
    {
        $condition = "";
        if ($uid) {
            $condition .= " and a.uid=$uid";
        }
        if ($status > -1) {
            $condition .= " and a.status=$status";
        }
        if ($is_all) {
            $condition .= " order by a.total_price desc ";
        }
        if ($page_size) {
            $condition .= "  limit " . $page_start . "," . $page_size;
        }

        $sql = " select a.*,b.username,b.avatar,b.nickname from " . tablename(t_redrain_user_flag) . " as a " .
            "left join " . tablename(t_fans) . " as b on b.uid = a.uid and b.themeid=$themeid" .
            " where a.themeid=$themeid  " . $condition;
        return db_select($sql);
    }

    /**
     * Desc:获取用户红包记录 区分分页 以及全部
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 10:13 上午
     * @param $themeid
     * @param int $uid
     * @param false $is_all
     * @param int $page_start
     * @param int $page_size
     * @return mixed
     */


    //获取今日
    public static function allDayMaxAmount($themeid,$config,$redrain_validity_hour){
        $date = date('Y-m-d',time());
        $where =" themeid = ".$themeid ." and status >=0 and date_format(created_at,'%Y-%m-%d')='$date'";
        if($redrain_validity_hour>0){
            $redrain_validity_minute =$redrain_validity_hour*60;
           $where .= " and  DATE_ADD(created_at,INTERVAL $redrain_validity_minute MINUTE)  > now()";
        }
        $sql = "select sum(a.max_amount) as all_amount from  (select  max(total_price) as max_amount from ".tablename(t_redrain_user_flag)." where ".$where ." group by uid) a";
        $day_all_max_amount = db_find($sql)['all_amount'];
        $day_remain_amount = $config['redrain_day_amount'];
        if (($day_all_max_amount+$config['redrain_once_amount']) < $config['redrain_day_amount']) {
            return $day_remain_amount - $day_all_max_amount ;
        } else {
            return 0;
        }
    }

    /**
     * Desc:获取用户可用最大的红包信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 1:58 下午
     * @param $themeid
     * @param $uid
     * @param $config
     * @return array
     */
    public static function getUserCanUseRedRainFlag($themeid, $uid, $config, $system)
    {
        $item = [];
        $list = self::getUserRedRainFlagList($themeid, $uid, true);
        $now_time = date("Y-m-d H:i:s", time());

        $theme = Theme::getThemeById($themeid);
        $error = self::checkBaseError($theme);
        $default_item = [
                    'id' => 0,
                    'uid' => $uid,
                    'themeid' => $themeid,
                    'status' => 0,
                    'total_price' => 0,
                    'created_at' => 0,
                    'convert_at' => 0,
                    'overdue_h' => 0,
                    'worker_id' => 0,
                ];


        if ($config['redrain_validity'] != 0) {
                foreach ($list as $key => $val) {
                    $overdue_time = date("Y-m-d H:i:s", strtotime("+ " . $config['redrain_validity'] . "hour", strtotime($val['created_at'])));
                    if ($now_time < $overdue_time) {
                        //将未过期的赋值新的数组
                        $new_item[] = [
                            'id' => $val['id'],
                            'uid' => $uid,
                            'themeid' => $themeid,
                            'status' => $val['status'],
                            'total_price' => $val['total_price'],
                            'created_at' => $val['created_at'],
                            'convert_at' => $val['convert_at'],
                            'overdue_h' => $val['overdue_h'],
                            'worker_id' => $val['worker_id'],
                        ];
                    } else {
                        //更新状态 已过期
                        if($val['status']<>2||$val['is_max']<>0){
                            $where = ['themeid' => $themeid, 'uid' => $uid, 'id' => $val['id']];
                            $update_data = ['status' => 2,'is_max' => 0];
                            self::updateFansRedRain($where, $update_data);
                           }
                    }

                    if ($new_item) {
                        $item = $new_item[0];
                        if($item['is_max']==0){
                            $where = ['themeid' => $themeid, 'uid' => $uid, 'id' => $item['id']];
                            $update_data = ['is_max' => 1];
                            self::updateFansRedRain($where, $update_data);
                        }
                    } else {
                        $item =  $default_item;
                    }
                }
            } else {
                $item = [
                    'id' => $list[0]['id'],
                    'uid' => $uid,
                    'themeid' => $themeid,
                    'status' => $list[0]['status'],
                    'total_price' => $list[0]['total_price'],
                    'created_at' => $list[0]['created_at'],
                    'convert_at' => $list[0]['convert_at'],
                    'overdue_h' => $list[0]['overdue_h'],
                    'worker_id' => $list[0]['worker_id'],
                ];
            }

        if(!empty($error)){
           $item = $default_item;
        }


        if ($item['worker_id']) {
            $r = Worker::getWokerName($system, $themeid, $item['worker_id']);
            $item['workername'] = $r['workername'];
        } else {
            $item['workername'] = '';
        }
        $theme = Theme::getThemeById($themeid);
        if(!$item['inputurl']&&$item['id']>0){
            $scene = MODULE_NAME . "-" . $theme['id'] . "-".$uid."-" . $theme['softkey']."-".$item['id'];
            //生成核销码
            $inputurl = Poster::CreateScene($system, $scene, $config, 'packageA/pages/redrain/verify/verify');

            $item['inputurl'] = $inputurl;
            //更新核销码地址
            self::updateFansRedRain(['themeid'=>$themeid,'uid'=>$uid,'id'=>$item['id']],['convert_url' =>$inputurl]);
        }

        // $inputurl = Poster::CreateScene($system, $scene, $config, 'pages/index/index');
        return $item;
    }

    //更新活动粉丝红包记录
    public static function updateFansRedRain($where, $update_data)
    {
        $res = db_update(t_redrain_user_flag, $update_data, $where);
        if (!$res) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Desc:获取用户指定类型的机会数据
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 3:42 下午
     * @param $themeid
     * @param $uid
     * @param $type
     * @return mixed
     */
    public static function getUserChanceList($themeid, $uid, $type)
    {
        $condition = "";
        if ($type) {
            $condition .= " and a.type='" . $type . "'";
        }
        $condition .= " order by a.created_at desc ";
        $sql = " select a.*,b.username,b.avatar,b.nickname from " . tablename(t_redrain_user_chance) . " as a " .
            "left join " . tablename(t_fans) . " as b on b.uid = a.uid and b.themeid=$themeid" .
            " where a.themeid=$themeid and a.uid=$uid " . $condition;
        return db_select($sql);
    }

    /**
     * Desc:获取好友助力列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/15 11:19 下午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getUserFriendHelpList($themeid, $uid)
    {
        $sql = " select a.*,b.username,b.avatar,b.nickname from " . tablename(t_redrain_user_chance) . " as a " .
            "left join " . tablename(t_fans) . " as b on b.uid = a.from_uid and b.themeid=$themeid" .
            " where a.themeid=$themeid and a.uid=$uid and a.type=2 ";
        return db_select($sql);
    }

    /**
     * Desc:获取我的红包中的助力记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 4:24 下午
     * @param $themeid
     * @param $fans
     * @param $config
     * @return array
     */
    public static function getUserFriendInfo($themeid, $fans, $config)
    {
        $show_friend_help = false;
        $info = [];
        if ($config['redrain_friend_view_num'] > 0 && $config['redrain_friend_view_limit'] > 0) {
            $show_friend_help = true;
            $list = self::getUserFriendHelpList($themeid, $fans['uid']);
            $new_time = time();
            $is_limit = false;
            $diff_user_num = 0;
            //判断是否达到总上限
            //已获得总机会
            $sql = "select sum(chance) as cnt from " . tablename(t_redrain_user_chance) .
                " where themeid=$themeid and type > 0 and chance > 0 and uid=" . $fans['uid'];
            $history_user_chance = db_find($sql)['cnt'];
            if ($history_user_chance > $config['redrain_chance_limit']) {
                $is_limit = true;
            }
            //判断好友到访的上限是否达到
            if (!$is_limit) {
                //获取好友到访增加的机会数
                $flag_total = self::getAddFlagTotalByType($fans['uid'], $themeid, 2, true);
                if ($flag_total < $config['redrain_friend_view_limit']) {
//                    if (!$flag_total){
//                        $no_add_flag_total = self::getAddFlagTotalByType($fans['uid'],$themeid,2,false);
//                        $diff_user_num = max(0,$config['redrain_friend_view_num']);
//                    }else{
                    //查找总数
                    $sql1 = " select count(*) as cnt from " . tablename(t_redrain_user_chance) .
                        " where themeid=$themeid and type = 2 and uid=" . $fans['uid'] . " and chance>=0 ";
                    $all_total = db_find($sql1)['cnt'];
                    $diff_user_num = $config['redrain_friend_view_num'] - ($all_total % $config['redrain_friend_view_num']);
//                    }
                } else {
                    $is_limit = true;
                }
            }
            //查找第一次助力记录
            //默认已过期
            $overdue_time = 0;
            $redrain_help_validity = $config['redrain_help_validity'];//助力有效期x小时
            $first_flag = self::getFirstHelpFlag($themeid, $fans['uid']);
            if (!empty($first_flag) && $redrain_help_validity > 0) {
                $first_flag_time = strtotime($first_flag['created_at']);
                $overdue_time = date('Y-m-d H:i:s', strtotime("+$redrain_help_validity hour", $first_flag_time));//助力截止时间

//                if ($validate_time2>$new_time){
//                    $overdue_time = $validate_time2-$new_time;
//                }
            }
            $info = [
                'list' => $list,//助力列表
                'is_limit' => $is_limit,//是否达到上限
                'diff_user_num' => $diff_user_num,//差几人增加一次机会
                'overdue_time' => $overdue_time,//过期时间戳
//                'redrain_friend_view_num'=>$config['redrain_friend_view_num'],//多少人助力增加一次
//                'redrain_friend_view_limit'=>$config['redrain_friend_view_limit'],//最多多少次
            ];
        }
        return ['show_friend_help' => $show_friend_help, 'info' => $info,'redrain_friend_view_num'=>$config['redrain_friend_view_num'],'redrain_friend_view_limit'=>$config['redrain_friend_view_limit']];
    }

    /**
     * Desc:获取前台需要的红包记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 5:44 下午
     * @param $themeid
     * @param $uid
     * @param $config
     * @return mixed
     */
    public static function getFrontUserRedRainList($themeid, $uid, $config, $system)
    {
        $sql = " select a.*,b.username,b.avatar,b.nickname from " . tablename(t_redrain_user_flag) . " as a " .
            "left join " . tablename(t_fans) . " as b on b.uid = a.uid and b.themeid=$themeid" .
            " where a.themeid=$themeid and a.uid=$uid order by a.created_at desc ";
        $list = db_select($sql);
        $new_time = date("Y-m-d H:i:s", time());
        $theme = Theme::getThemeById($themeid);
        $error = self::checkBaseError($theme);

        foreach ($list as $key => $val) {
            if($error){
                $list[$key]['status'] = 2;
            }else{
                if ($config['redrain_validity'] > 0) {
                    $overdue_time = date("Y-m-d H:i:s", strtotime("+ " . $config['redrain_validity'] . "hour", strtotime($val['created_at'])));

                    if ($overdue_time <= $new_time) {
                        $list[$key]['status'] = 2;
                    } else {
//                    $list[$key]['overdue_h']=strtotime("+ ".$config['redrain_validity']."hour",strtotime($val['created_at']))-time();
                        $list[$key]['overdue_h'] = $overdue_time;
                    }
                }
            }
            if ($val['status'] == 1) {
                if ($system['redrain'] == 1) {
                    $list[$key]['title'] = '消费抵扣';
                } elseif ($system['redrain'] == 2) {
                    $list[$key]['title'] = '已提现';
                }
            } else {
                $list[$key]['title'] = '红包来袭';
            }
            unset($list[$key]['avatar']);
            unset($list[$key]['id']);
            unset($list[$key]['nickname']);
            unset($list[$key]['themeid']);
            unset($list[$key]['updated_at']);
            unset($list[$key]['username']);
        }
        return $list;
    }

    /**
     * Desc:获取前台展示的机会记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 6:21 下午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getFrontUserChanceList($themeid, $uid)
    {
        $list = self::getUserChanceList($themeid, $uid, 0);
        $title = '';
        foreach ($list as $key => $val) {
            switch ($val['type']) {
                case 1:
                    $title = '分享朋友圈获得机会';
                    $list[$key]['title'] = $title;
                    break;
                case 2:
                    $title = '好友助力获得机会';
                    $list[$key]['title'] = $title;
                    break;
                case 3:
                    $title = '分享好友获得机会';
                    $list[$key]['title'] = $title;
                    break;
                case 4:
                    $title = '官方赠送机会';
                    $list[$key]['title'] = $title;
                    break;
                case 5:
                    $title = '系统补发机会';
                    $list[$key]['title'] = $title;
                    break;
                case 9:
                    $title = '好友下单';
                    $list[$key]['title'] = $title;
                    break;
                case -1:
                    $title = '机会使用';
                    $list[$key]['title'] = $title;
                    break;
                default:
                    break;
            }
            unset($list[$key]['themeid']);
            unset($list[$key]['updated_time']);
            unset($list[$key]['from_uid']);
            unset($list[$key]['id']);
            unset($list[$key]['is_tips']);
            unset($list[$key]['admin_name']);
            if ($val['chance'] > 0) {
                $list[$key]['chance'] = '+' . $val['chance'];
            }
        }
        return $list;
    }

    /**
     * Desc:插入用户红包记录以及更新其他类型红包记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 5:34 下午
     * @param $themeid
     * @param $fans
     * @param $config
     * @param $amount
     * @param $chanceId
     */
    public static function insertUserRedRainItem($themeid, $fans, $config, $amount, $chanceId)
    {
        $has_max_redrain_flag = self::getUserMaxRedRainItem($themeid, $fans['uid']);
        if ($has_max_redrain_flag) {
            if ($has_max_redrain_flag['total_price'] <= $amount) {
                //更新
                $where = ['id' => $has_max_redrain_flag['id']];
                $update_data = ['is_max' => 0];
                self::updateFansRedRain($where, $update_data);
                $insert_data = [
                    'uid' => $fans['uid'],
                    'themeid' => $themeid,
                    'total_price' => $amount,
                    'is_max' => 1,
                    'convert_code' => GetRandConvertCode(),
                    'overdue_h' => $config['redrain_validity'],
                    'chance_id' => $chanceId,
                ];
            } else {
                $insert_data = [
                    'uid' => $fans['uid'],
                    'themeid' => $themeid,
                    'total_price' => $amount,
                    'is_max' => 0,
                    'convert_code' => GetRandConvertCode(),
                    'overdue_h' => $config['redrain_validity'],
                    'chance_id' => $chanceId,
                ];
            }
        } else {
            $insert_data = [
                'uid' => $fans['uid'],
                'themeid' => $themeid,
                'total_price' => $amount,
                'is_max' => 1,
                'convert_code' => GetRandConvertCode(),
                'overdue_h' => $config['redrain_validity'],
                'chance_id' => $chanceId,
            ];
        }
        if ($insert_data) {
            self::insertUserRedRain($insert_data);
        }

    }

    /**
     * Desc:获取用户最大红包记录  不考虑过期
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 4:44 下午
     * @param $themeid
     * @param $uid
     * @return mixed
     */
    public static function getUserMaxRedRainItem($themeid, $uid)
    {
        $sql = " select a.*,b.username,b.avatar,b.nickname from " . tablename(t_redrain_user_flag) . " as a " .
            "left join " . tablename(t_fans) . " as b on b.uid = a.uid and b.themeid=$themeid" .
            " where a.themeid=$themeid and a.uid=$uid order by a.total_price desc ";
        return db_find($sql);
    }

    /**
     * Desc:获取所有用户已提现的总金额
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 6:33 下午
     * @param $themeid
     * @return mixed
     */
    public static function getAllRedRainReturnAmount($themeid)
    {
        $sql = " select sum(total_price) as amount from " . tablename(t_redrain_user_flag) . " where themeid=$themeid and status=1";
        return db_find($sql)['amount'];
    }

    /**
     * Desc:获取当前活动剩余可用奖金池金额
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 7:21 下午
     * @param $themeid
     * @param $config
     * @return int|mixed
     */
    public static function formatAllRedrainAmount($themeid, $config)
    {
        $list = self::getUserRedRainFlagList($themeid, 0, true, 0, 0, 0);
        $flag_ids = '';
        $now_time = date("Y-m-d H:i:s", time());
        foreach ($list as $key => $val) {

            $overdue_time = date("Y-m-d H:i:s", strtotime("+ " . $config['redrain_validity'] . "hour", strtotime($val['created_at'])));
            if ($now_time < $overdue_time) {
                $flag_ids .= $val['id'] . ',';
            } else {
                if ($config['redrain_validity'] != 0) {
                    //更新状态 已过期
                    $where = ['themeid' => $themeid, 'id' => $val['id']];
                    $update_data = ['status' => 2];
                    self::updateFansRedRain($where, $update_data);
                }
            }
        }
        $flag_ids = rtrim($flag_ids, ',');
        if ($flag_ids) {
            //未过期的所有用户的记录ids
            //获取所有用户可用的最大红包的总和
//            $sql = " select uid, max(total_price) as max_amount,sum(max_amount) as total_amount from ".tablename(t_redrain_user_flag).
//            " where id in (".$flag_ids.") group by uid";
            $sql = " select uid, sum(total_price) as total_amount from " . tablename(t_redrain_user_flag) .
                " where is_max=1 and id in (" . $flag_ids . ") group by uid";
            $all_lock_amount = db_find($sql)['total_amount'];
        } else {
            $all_lock_amount = 0;
        }
        $all_used_amount = self::getAllRedRainReturnAmount($themeid);
        if (($all_lock_amount + $all_used_amount + $config['redrain_once_amount']) < $config['redrain_total_amount']) {
            return ($config['redrain_total_amount'] - $all_lock_amount - $all_used_amount);
        } else {
            return 0;
        }
    }

    /**
     * Desc:获取机会攻略
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 8:25 下午
     * @param $themeid
     * @param $fans
     * @param $config
     * @param $system
     */
    public static function getUserMethod($_C, $_S, $themeid, $fans)
    {
        $temp_arr = [];
        //判断获得红包机会总上限与已获得机会次数，取得剩余机会次数
        $totalChance = $_C['redrain_chance_limit'];
        $sql = "select sum(chance) as cnt from " . tablename(t_redrain_user_chance) .
            " where themeid=$themeid and type > 0 and chance > 0 and uid=" . $fans['uid'];
        $allChance = db_find($sql)['cnt'];
        if ($allChance >= $totalChance) {
            return $temp_arr;
        }
        //三项配置:分享朋友圈，分享朋友/群，好友到访
        //分享朋友圈获得机会次数与总剩余次数做对比
        $add_chance = 0;
        //判断是否存在分享朋友圈的记录  以及今日记录数
        $all_flag_total = self::getFlagTotal($fans['uid'], $themeid, 1);
        if ($all_flag_total < 3) {
            //小于3天
            if ($all_flag_total == 0) {
                //第一天
                $add_chance = (int)$_C['redrain_first_share_moment'];//第一天
            } elseif ($all_flag_total == 1) {
                //第二天
                $today_type_success_total = self::getAddFlagTotalByType($fans['uid'], $themeid, 1, true, true);
                if (!$today_type_success_total) {
                    $add_chance = (int)$_C['redrain_second_share_moment'];//第二天
                }
            } elseif ($all_flag_total == 2) {
                //第三天
                $today_type_success_total = self::getAddFlagTotalByType($fans['uid'], $themeid, 1, true, true);
                if (!$today_type_success_total) {
                    $add_chance = (int)$_C['redrain_third_share_moment'];//第三天
                }
            }
        }
        if ($add_chance > $totalChance - $allChance) {
            $add_chance = $totalChance - $allChance;
        }
        if ($add_chance > 0) {
            array_push($temp_arr, "今天分享到朋友圈可获得" . $add_chance . "次机会");
        }
        //分享好友
        $add_chance2 = 0;
        $all_flag_total2 = self::getFlagTotal($fans['uid'], $themeid, 3);
        if ($all_flag_total2 < 3) {
            //小于3天
            if ($all_flag_total2 == 0) {
                //第一天
                $add_chance2 = $_C['redrain_first_share_friend'];
            } elseif ($all_flag_total2 == 1) {
                //第二天
                $today_type_success_total = self::getAddFlagTotalByType($fans['uid'], $themeid, 3, true, true);
                if (!$today_type_success_total) {
                    $add_chance2 = $_C['redrain_second_share_friend'];
                }
            } elseif ($all_flag_total2 == 2) {
                //第三天
                $today_type_success_total = self::getAddFlagTotalByType($fans['uid'], $themeid, 3, true, true);
                if (!$today_type_success_total) {
                    $add_chance2 = $_C['redrain_third_share_friend'];
                }
            }
        }
        if ($add_chance2 > $totalChance - $allChance) {
            $add_chance2 = $totalChance - $allChance;
        }
        if ($add_chance2 > 0) {
            array_push($temp_arr, "今天分享到好友群可获得" . $add_chance2 . "次机会");
        }
        //开始判断好友到访
        //好友到访，x个好友到访获得1次抽奖机会，最多x次
        //判断是否在助力时间内
        $theme = Theme::getThemeById($themeid);
        $friendViewStartTime = $theme['begintime'];//默认活动开始时间
        $friendViewEndTime = $theme['endtime'];//默认活动结束时间
        if ($_C['redrain_help_validity']) {
            //查找第一次助力时间
            $firstView = self::getFirstHelpFlag($themeid, $fans['uid']);
            if (!empty($firstView)) {
                $friendViewStartTime = strtotime($firstView['created_at']);//助力开始时间
                $friendViewEndTime = strtotime("+" . $_C['redrain_help_validity'] . " days", strtotime($firstView['created_at']));//助力结束时间
            }
        }

        $add_chance3 = 0;//邀请几个好友到访获得一次机会；
        if ($_C['redrain_friend_view_limit'] > 0 && (time() < $friendViewEndTime && $friendViewStartTime <= time())) {
            //好友到访已获得机会次数与配置次数做对比
            //查找到访获得的次数
            $sql1 = " select sum(chance) as cnt from " . tablename(t_redrain_user_chance) .
                " where themeid=$themeid and type = 2 and uid=" . $fans['uid'] . " and chance>0 ";
            $helpChance = db_find($sql1)['cnt'];
            if ($helpChance < $_C['redrain_friend_view_limit']) {
                //查找到访总人数
                $sql2 = " select count(*) as cnt from " . tablename(t_redrain_user_chance) .
                    " where themeid=$themeid and type = 2 and uid=" . $fans['uid'] . " and chance>=0 ";
                $all_total = db_find($sql2)['cnt'];
                $add_chance3 = $_C['redrain_friend_view_num'] - ($all_total % $_C['redrain_friend_view_num']);
            }
        }
        if ($add_chance3 > 0) {
            array_push($temp_arr, '邀请' . $add_chance3 . '位好友到访可获得一次机会');
        }
        return $temp_arr;
    }

    /**
     * Desc:用户红包使用状态修改
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 9:15 下午
     * @param $themeid
     * @param $fans
     * @param $target_id
     * @param $system
     * @return bool
     */
    public static function apiUseRedRainFlag($themeid,$fans,$target_id,$system,$worker_id=0)
    {
        $res = self::getUserRedRainFlagItemByWhere(['id'=>$target_id,'themeid'=>$themeid,'uid'=>$fans['uid']]);
        if ($res && $res['status']==0){
            $where = ['themeid'=>$themeid,'uid'=>$fans['uid'],'id'=>$res['id']];
            $update_data = ['status'=>1,'worker_id'=>$worker_id,'convert_at'=>date('Y-m-d H:i:s')];
            $update_res = self::updateFansRedRain($where,$update_data);
            //更新所有正常为已提现 不可提现状态
            $where1 = ['themeid' => $themeid, 'uid' => $fans['uid'], 'status' => 0];
            $update_data1 = ['status' => 3];
            $update_res1 = self::updateFansRedRain($where1, $update_data1);
            //提现模式
            if ($system['redrain'] == 2) {
                //插入提现记录表
                $ordersn = getMillisecond();
                $data = array(
                    'uniacid'    => $fans['uniacid'],
                    'themeid'    => $themeid,
                    'recordid'   => 0,
                    'ordersn'    => $ordersn,
                    'type'       => 13,
                    'openid'     => $fans['openid'],
                    'uid'     => $fans['uid'],
                    'addtime'    => TIMESTAMP,
                    'fee'        => $res['total_price'],
                    'fopenid'    => $fans['fopenid'],
                    'fromuid'    => $fans['uid'],
                    'openid_old'     => $fans['openid_old'],
                    'uid_old'     => $fans['uid_old'],
                    'fopenid_old'    => $fans['fopenid_old'],
                    'fromuid_old'    => $fans['fromuid_old'],
                    'status'     =>0,
                );
                //提现
                $id =   Comm::add_share_comm($data);
                $comm = db_get(t_comm,['id'=>$id]);
                $totalpayfee = Order::getRealByThemeIdnew($themeid)-$comm['fee'] ;
                if ($totalpayfee>0){
                    Fee::commRecord($comm,$system);
                }
            }
            if ($update_res) {
                return true;
            } else {

                return false;
            }
        } else {
            return false;
        }
    }


    //抵扣回调
    public static function apiUseDkRedRainFlag($themeid,$fans,$target_id,$system,$record_id)
    {
        $res = self::getUserRedRainFlagItemByWhere(['id'=>$target_id,'themeid'=>$themeid,'uid'=>$fans['uid']]);
        if ($res && $system['redrain']==1){
            //订单id
            $where1 = ['themeid'=>$themeid,'uid'=>$fans['uid'],'record_id'=>$record_id];
            $update_data1 = ['record_id'=>0];
            self::updateFansRedRain($where1,$update_data1);

            $where2 = ['themeid'=>$themeid,'uid'=>$fans['uid'],'id'=>$res['id']];
            $update_data2 = ['record_id'=>$record_id];
            self::updateFansRedRain($where2,$update_data2);

        }else{
            return false;
        }
    }


    //支付回调
    public static function payCallback($themeid,$uid,$record_id){
        $where = ['themeid'=>$themeid,'uid'=>$uid,'record_id'=>$record_id];
        $update_data = ['status'=>1,'convert_at'=>date('Y-m-d H:i:s')];
        $update_res = self::updateFansRedRain($where,$update_data);
        //更新所有正常为已提现 不可提现状态
        $where1 = ['themeid'=>$themeid,'uid'=>$uid,'status'=>0];
        $update_data1 = ['status'=>3];
        $update_res1 = self::updateFansRedRain($where1,$update_data1);
    }

    /**
     * Desc:获取查询的用户红包记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 9:19 下午
     * @param $where
     * @return mixed
     */
    public static function getUserRedRainFlagItemByWhere($where)
    {
        return db_get(t_redrain_user_flag, $where);
    }

    /**
     * Desc:获取随机实例数组
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/20 4:26 下午
     * @return array
     */
    public static function makeRandTempArr()
    {
        $temp_arr = [];
        $redpacket_total = rand(4, 6);
        $gold_total = rand(2, 3);
        $bomb_total = rand(1, 2);
        for ($i = 1; $i <= $redpacket_total; $i++) {
            array_push($temp_arr, ['type' => 'redpacket']);
        }
        for ($j = 1; $j <= $gold_total; $j++) {
            array_push($temp_arr, ['type' => 'gold']);
        }
        for ($b = 1; $b <= $bomb_total; $b++) {
            if (count($temp_arr) < 10) {
                array_push($temp_arr, ['type' => 'bomb']);
            }
        }
        if (count($temp_arr) < 10) {
            array_push($temp_arr, ['type' => 'redpacket']);
        }
        if (count($temp_arr) < 10) {
            array_push($temp_arr, ['type' => 'gold']);
        }
        if (count($temp_arr) < 10) {
            array_push($temp_arr, ['type' => 'bomb']);
        }
        shuffle($temp_arr);
        return $temp_arr;
    }

    /**
     * @param $themeid
     * @param $_C
     * @return mixed
     */
    public static function getUserMaxRedPacket($themeid, $_C)
    {
        global $_G;
        $uid = $_G['member']['uid'];
        if (empty($uid)){
            return array(
                'redrain_id'=>0,
                'text'=>'#br立即抢购'
            );
        }else{
            $sql = "select id,total_price from " . tablename(t_redrain_user_flag) . " where themeid=$themeid and uid = $uid and status = 0 ";
            $hours = $_C['redrain_validity'];//0代表不过期
            if ($hours != 0) {
                //计算最小创建时间
                $minStartTime = date('Y-m-d H:i:s', strtotime("-$hours hours"));
                $sql .= " and created_at >= '$minStartTime'";
            }
            $sql .= " order by total_price desc ";
            $redrain_info =  db_find($sql);
            if(isset($redrain_info['id']) && $redrain_info['id']>0){
                return array(
                    'redrain_id'=>$redrain_info['id'],
                    'text'=>'#br下单红包立减'.$redrain_info['total_price'].'元'
                );
            }else{
                return array(
                    'redrain_id'=>0,
                    'text'=>'#br立即抢购'
                );
            }
        }
    }

    /**
     * 根据红包ID查询红包金额
     * @param $id
     * @param $_C
     * @return array(
     *     'error'=>1,  // 1 代表红包信息有错误 0 代表红包信息正确
     *     'msg'=>'错误信息',
     *     'total_price'=>2.75 // 返回红包金额
     * )
     */
    public static function getRedPacketInfoById($id, $_C)
    {
        $packetInfo = db_find("select id,themeid,uid,created_at,status,total_price from " . tablename(t_redrain_user_flag) . " where id=$id ");
        if (empty($packetInfo)){
            return [
                'error'=>1,
                'msg'=>'未找到红包信息！'
            ];
        }
        if ($packetInfo['status'] == 1){
            return [
                'error'=>1,
                'msg'=>'此红包已使用！'
            ];
        }
        if ($packetInfo['status'] == 3){
            return [
                'error'=>1,
                'msg'=>'已有其他红包使用！'
            ];
        }
        $hours = $_C['redrain_validity'];//0代表不过期
        if ($hours != 0) {
            //计算最小创建时间
            $minStartTime = strtotime("-$hours hours 30 minutes");//增加半小时有效期
            if(strtotime($packetInfo['created_at']) < $minStartTime){
                return [
                    'error'=>1,
                    'msg'=>'红包已过期！'
                ];
            }
        }
        //没有问题返回红包金额
        return [
            'error'=>0,
            'msg'=>'',
            'total_price'=>$packetInfo['total_price']
        ];
    }

    public static function adminInsertChance($themeid, $config, $fans, $type, $commcountxuni, $admin_name)
    {
        $main_chance_limit = $config['redrain_chance_limit'];
        $sql = "select sum(chance) as cnt from " . tablename(t_redrain_user_chance) .
            " where themeid=$themeid and type > 0 and chance > 0 and uid=" . $fans['uid'];
        $history_user_chance = db_find($sql)['cnt'];
        $add_chance = $commcountxuni;
        if ($add_chance > 0 && $history_user_chance >= $main_chance_limit) {
            return [
                'error'=>1,
                'msg'=>'此用户达到机会上限！'
            ];
        }

        //判断所有用户有效期内的最大红包金额总和 是否大于奖金池
        if($config['redrain_total_amount']>0){
            //奖金池存在奖金
            $remain_amount = self::formatAllRedrainAmount($themeid, $config);
            if ($remain_amount <= 0) {
                return [
                    'error'=>1,
                    'msg'=>'红包金额已发放完！'
                ];
            }
        }
        //查找是否有已使用红包
        $used_redrain = self::getUserRedRainFlagTotal($themeid, $fans['uid'], 1);
        if ($used_redrain > 0) {
            return [
                'error'=>1,
                'msg'=>'此用户已使用红包！'
            ];
        }
        //将要增加的机会与总剩余机会做比较
        if ($add_chance > 0 && $main_chance_limit > $history_user_chance && $add_chance > ($main_chance_limit - $history_user_chance)) {
            $add_chance = $main_chance_limit - $history_user_chance;
        }
        $insert_data = [
            'uid' => $fans['uid'],
            'themeid' => $themeid,
            'type' => $type,
            'chance' => $add_chance,
            'is_tips' => 0,
            'from_uid' => 0,
            'admin_name' => $admin_name,
        ];
        //查找新用户机会信息
        $new_fans = self::getFansInfoByWhere(['themeid' => $themeid, 'uid' => $fans['uid']]);
        $insert_data['changed_chance'] = $new_fans['jihui'] + $add_chance;
        // used_id 使用的机会ID，used_type 使用的机会来源，0未使用 1转发朋友圈 2好友到访 3转发好友 4商家赠送 5管理员增加，remaining_chance 剩余的机会，changed_chance 变化后的机会数
        $insert_data['used_id'] = 0;
        $insert_data['used_type'] = 0;
        $insert_data['remaining_chance'] = $add_chance;
        $res = self::insertUserChance($insert_data);
        if(!$res){
            return [
                'error'=>1,
                'msg'=>'添加红包雨机会失败！'
            ];
        }
        return [
            'error'=>0,
            'msg'=>'',
            'jihui'=>$new_fans['jihui'] + $add_chance
        ];
    }
}